package core

import "fmt"

import (
	"log"
	"os"
	"strconv"
	"time"
)

var loglevel int

func init() {
	loglevel = 1
	InitConfig()
	level := ConfigInt("log_level")
	SetLogLevel(level)
	_, err := os.Stat(".\\log")
	if os.IsNotExist(err) {
		os.Mkdir(".\\log", 0777)
		os.Chmod(".\\log", 0777)
	}
	log.SetFlags(log.Ldate |log.Ltime | log.Lmicroseconds | log.Lshortfile)
}

func SetLogLevel(level int) {
	loglevel = level
}

func openLog() *os.File {
	a, b, c := time.Now().Date()
	d := int(b)
	var e string
	switch d {
	case 1, 2, 3, 4, 5, 6, 7, 8, 9:
		e = "0" + strconv.Itoa(d)
	case 10, 11, 12:
		e = strconv.Itoa(d)
	}
	title := "./log/" + strconv.Itoa(a) + e + strconv.Itoa(c) + ".log"
	file, _ := os.OpenFile(title, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	return file
}

func Debug(mes string, err interface{}) {
	if loglevel <= DEBUG {
		f := openLog()
		defer f.Close()
		log.SetOutput(f)
		log.SetPrefix("[DEBUG]:")
		log.Printf("%v%v\r\n", mes, err)
	}
	fmt.Println("DEBUG", time.Now().Local(), ":", mes, err)
}

func Info(mes string, err interface{}) {
	if loglevel <= INFO {
		f := openLog()
		defer f.Close()
		log.SetOutput(f)
		log.SetPrefix("[INFO]:")
		log.Printf("%v%v\r\n", mes, err)
	}
	fmt.Println("INFO", time.Now().Local(), ":", mes, err)
}

func Warn(mes string, err interface{}) {
	if loglevel <= WARN {
		f := openLog()
		defer f.Close()
		log.SetOutput(f)
		log.SetPrefix("[WARN]:")
		log.Printf("%v%v\r\n", mes, err)
	}
	fmt.Println("WARN", time.Now().Local(), ":", mes, err)
}

func Error(mes string, err interface{}) {
	if loglevel <= ERROR {
		f := openLog()
		defer f.Close()
		log.SetOutput(f)
		log.SetPrefix("[ERROR]:")
		log.Printf("%v%v\r\n", mes, err)
	}
	fmt.Println("ERROR", time.Now().Local(), ":", mes, err)
}
